package com.app.service;

import com.app.config.SolrConfig;
import com.app.model.main.Article;
import com.app.model.main.UserInfo;
import com.app.model.solr.ArticleItem;
import com.app.model.solr.SolrFlag;
import com.app.model.solr.UserItem;;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * Created by Lichaojie on 2017/3/13. It's a beautiful day.
 */
@Service
public class SolrService {

    private final Logger logger = Logger.getLogger(SolrService.class);

    private final String articleUrl = SolrConfig.solr_server + "/solr/campus_article";//浏览器http://123.56.29.77:8983/solr/#/campus-article
    private final String userUrl = SolrConfig.solr_server +  "/solr/campus_user";

    /**
     * true/false 判断是否加入成功
     * @param object
     * @param <T>
     * @return
     */
    public <T> boolean addField(T object){
        if(object instanceof UserInfo){
            UserInfo userInfo = (UserInfo)object;
            SolrClient solrClient = new HttpSolrClient.Builder(userUrl).build();

            String labelString = userInfo.getLabel();

            UserItem userItem = new UserItem();
            userItem.setId(userInfo.getId())
                    .setLabel(labelString)
                    .setGender(userInfo.getGender()==0?"女":"男")
                    .setNickName(userInfo.getNickName())
                    .setSchool(userInfo.getSchool())
                    .setEducation(userInfo.getEducation())
                    .setIntroduction(userInfo.getIntroduction());

            try{
                solrClient.addBean(userItem);
                solrClient.commit();
            }catch (SolrServerException e){
                return false;
            }catch (IOException e){
                return false;
            }

        }else if(object instanceof Article){
            Article article = (Article)object;
            SolrClient solrClient = new HttpSolrClient.Builder(articleUrl).build();

            String labelString = article.getLabel();

            ArticleItem articleItem = new ArticleItem();
            articleItem.setId(article.getId())
                    .setTitle(article.getTitle())
                    .setLabel(labelString)
                    .setContent(article.getContent())
                    .setType(article.getType())
                    .setUserId(article.getUserId());

            try{
                solrClient.addBean(articleItem);
                solrClient.commit();
            }catch (SolrServerException e){
                return false;
            }catch (IOException e){
                return false;
            }
        }else{
            return false;
        }
        return true;
    }

    /**
     * 根据id删除搜索条目
     * @param id
     * @param flag
     * @return
     */
    public boolean delete(String id,int flag){
        String urlString = "";
        if(flag == SolrFlag.ARTICLE){
            urlString = articleUrl;
        }else{
            urlString = userUrl;
        }
        SolrClient solrClient = new HttpSolrClient.Builder(urlString).build();
        try {
            solrClient.deleteById(id);
            solrClient.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 搜索用户，默认搜索全部
     * @param queryString
     * @param flag
     * @param start
     * @param rows
     * @return
     */
    public List query(String queryString,int flag,int start,int rows){
        return doQuery(querySetting(queryString,start,rows,(byte)2),SolrFlag.USER);
    }

    //将关键字和单个用户的信息进行匹配，目的为了获得匹配的得分
    public List queryWithUserId(String queryString,int flag,int start,int rows,long userId){
        return doQuery(querySettingWithId(queryString,start,rows,(byte)2,userId),SolrFlag.USER);
    }

    /**
     * 搜索帖子，type表示搜索帖子的类型 0-求助帖，1-分享贴，2-全部
     * @param queryString
     * @param flag
     * @param start
     * @param rows
     * @param type
     * @return
     */
    public List queryWithFilter(String queryString,int flag,int start,int rows,byte type){
        return doQuery(querySetting(queryString,start,rows,type),flag);
    }

    /**
     * 在指定用户的帖子里进行查找（用于搜索用户时匹配度的计算）
     * @param queryString
     * @param flag
     * @param start
     * @param rows
     * @param type
     * @param userId
     * @return
     */
    public List queryWithTypeAndUserId(String queryString,int flag,int start,int rows,byte type,long userId){
        return doQuery(querySettingWithTypeAndUserId(queryString, start, rows, type, userId),flag);
    }

    private List doQuery(SolrQuery query,int flag){

        String urlString;
        if(flag == SolrFlag.ARTICLE){
            urlString = articleUrl;
        }else{
            urlString = userUrl;
        }
        //logger.info("urlString : " + urlString);
        SolrClient solrClient = new HttpSolrClient.Builder(urlString).build();

        QueryResponse response;
        try {
            response = solrClient.query(query);
        } catch (SolrServerException e) {
            e.printStackTrace();
            return new ArrayList();
        } catch (IOException e) {
            e.printStackTrace();
            return new ArrayList();
        }
        SolrDocumentList list = response.getResults();

//        logger.info("list.size() : " + list.size());
//        for (SolrDocument solrDocument : list){
//            logger.info(">>>> : " + solrDocument.getFieldValue("id"));
//        }

        return list;
    }

    /**
     * 设置查询参数
     * @param queryString
     * @param start
     * @param rows
     * @param type 0/1表示帖子的类型，2表示搜索全部
     * @return
     */
    private SolrQuery querySetting(String queryString,int start,int rows,byte type){
        SolrQuery query = new SolrQuery();
        if(type == 0 || type == 1){
            query.set("fq","type:" + type);
//            logger.info("type : " + type);
        }
//        logger.info("start : " + start);
//        logger.info("rows : " + rows);
//        logger.info("queryString : " + queryString);

        query.set("fl", "id,score");//控制查询结果返回的域
        query.set("q", queryString);//查询关键词
        query.set("start",start * rows);
        query.set("rows", rows);
        return query;
    }

    //搜索文章的参数设定
    private SolrQuery querySettingWithTypeAndUserId(String queryString,int start,int rows,byte type,long userId){
        SolrQuery query = new SolrQuery();
        if(type == 0 || type == 1){
            query.set("fq","type:" + type);
//            logger.info("type : " + type);
        }
        query.set("fq","userId:" + userId);
//        logger.info("start : " + start);
//        logger.info("rows : " + rows);
//        logger.info("queryString : " + queryString);

        query.set("fl", "id,score");//控制查询结果返回的域
        query.set("q", queryString);//查询关键词
        query.set("start",start * rows);
        query.set("rows", rows);
        return query;
    }

    //搜索用户的参数设定
    private SolrQuery querySettingWithId(String queryString,int start,int rows,byte type,long userId){
        SolrQuery query = new SolrQuery();
        if(type == 0 || type == 1){
            query.set("fq","type:" + type);
//            logger.info("type : " + type);
        }
        query.set("fq","id:" + userId);
//        logger.info("start : " + start);
//        logger.info("rows : " + rows);
//        logger.info("queryString : " + queryString);

        query.set("fl", "id,score");//控制查询结果返回的域
        query.set("q", queryString);//查询关键词
        query.set("start",start * rows);
        query.set("rows", rows);
        return query;
    }






    /**
     * 未使用
     * @param article
     * @return
     */
    private String getArticleSolrString(Article article){
        String solrString = "";

        String labelString = article.getLabel();

        String[] strings = labelString.split(",");

        solrString += ("title:" + article.getTitle() + ",");
        solrString += ("content:" + article.getContent() + ",");
        solrString += ("label:");

        for (String s : strings){
            solrString += (s + " ");
        }

        return solrString;
    }

    /**
     * 未使用
     * @param userInfo
     * @return
     */
    private String getUserInfoSolrString(UserInfo userInfo){
        String solrString = "";

        String labelString = userInfo.getLabel();

        String[] strings = labelString.split(",");

        solrString += ("nickName:" + userInfo.getNickName() + ",");
        solrString += ("school:" + userInfo.getSchool() + ",");
        solrString += ("education:" + userInfo.getEducation() + ",");
        solrString += ("gender" + (userInfo.getGender() == (byte)0?"女":"男") + ",");
        solrString += ("label:" );

        for (String s : strings){
            solrString += (s + " ");
        }

        solrString += ",";
        solrString += ("introduction:" + userInfo.getIntroduction() );
        return solrString;

    }
}
